package com.atguigu.paymentdemo.schedule;

import com.atguigu.paymentdemo.entity.OrderInfo;
import com.atguigu.paymentdemo.enums.OrderStatus;
import com.atguigu.paymentdemo.service.OrderInfoService;
import com.atguigu.paymentdemo.service.PaymentInfoService;
import com.atguigu.paymentdemo.service.impl.WxNavicateService;

import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @projectName: payment-demo
 * @package: com.atguigu.paymentdemo.schedule
 * @className: PaySchedule
 * @author: 躺着认真玩
 * @description: 微信native支付兜底
 * @date: 2025/6/9 20:45
 * @version: 1.0
 */
@Component
public class PaySchedule {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private WxNavicateService wxNavicateService;
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Scheduled(cron = "0/30 * * * * *")
    public void payHandle(){
        // 查询超时5分钟未支付的订单
        List<OrderInfo> list = orderInfoService.lambdaQuery()
                .eq(OrderInfo::getOrderStatus, OrderStatus.NOTPAY.getType())
                .orderByAsc(OrderInfo::getCreateTime)
                .lt(OrderInfo::getCreateTime, LocalDateTime.now().minusMinutes(5))
                .list();
        // 调用微信支付接口-查看订单
        for (OrderInfo orderInfo : list) {
            String orderNo = orderInfo.getOrderNo();
            Transaction transaction = wxNavicateService.queryOrderByOutOrderNo(orderNo);
            if (!transaction.getTradeState().toString().equals(OrderStatus.SUCCESS.getType())){
                //     关闭账单
                wxNavicateService.closeOrder(orderNo);
                orderInfoService.updatePayStatusByOrderNo(orderNo,OrderStatus.CLOSED.getType());
                return;
            }
            //     修改订单支付状态  支付记录
            paymentInfoService.insertInfo(transaction);
            orderInfoService.updatePayStatusByOrderNo(orderNo,OrderStatus.SUCCESS.getType());
        }
        return;
    }
}
